package quick.api.app.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import webdm.business.util.DateTimeUtil;

import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class FormatArticleData {

    /**
     * 格式化文章的时间
     */
    private static void formatTime (JSONObject article) {
        if (article.containsKey("create_time")) {
            long createTime = article.getLong("create_time");
            if (createTime > 0) {
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date date = new Date();
                date.setTime(createTime);
                article.put("create_time_string", simpleDateFormat.format(date));
            }
        }
    }

    private static void formatDescription(JSONObject article) {
        String description = article.getString("description");
        if (StringUtils.isEmpty(description)) {

            String body = article.getString("body");
            String name = article.getString("name");

            if (StringUtils.isNotEmpty(body)) {
                description = body.replaceAll("<.*?>", "").replaceAll("\\s+", " ").trim();
                if (StringUtils.isNotEmpty(description) && description.length() > 10) {
                    article.put("description", description.substring(0, Math.min(200, description.length())));
                } else {
                    article.put("description", name);
                }
            } else {
                article.put("description", name);
            }
        }
    }

    private static void formatTag(JSONObject article) {
        String tag = article.getString("tag");
        if (StringUtils.isNotEmpty(tag)) {

            String arr[] = tag.split(",");
            if (arr != null && arr.length > 0) {
                List<String> tagList = new ArrayList<>(16);
                for(String item : arr){

                    String temp = item.trim().replaceAll("^\\[+", "").replaceAll("\\]$", "");
                    if (StringUtils.isNotEmpty(temp)) {
                        tagList.add(temp);
                    }
                }
                if (tagList.size() > 0) {
                    article.put("tag", tagList);
                }
            }
            article.put("tag_string", tag);
        }
    }


    public static void formatArticle(JSONObject article) {
        if (article != null) {
            FormatObjectExt.format(article);
            formatTime(article);
            formatDescription(article);
            formatTag(article);
        }
    }
}
